package com.zrh.jsd.service.studydemo.rewrite_hashcode_equals;

import java.util.HashMap;

// 为什么要重写hashCode和equals
class KeyRewrite {
    private Integer id;

    public Integer getId() {
        return id;
    }

    public KeyRewrite(Integer id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }

    @Override
    // 如果不重写，在对象保存时k1和k2会保存为两个，因为他们的地址不一样。
    // 重写之后会保存为一个。
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof KeyRewrite)) {
            return false;
        } else {
            return this.getId().equals(((KeyRewrite) obj).getId());
        }
    }
}

public class RewriteHashCode {
    public static void main(String[] args) {
        KeyRewrite k1 = new KeyRewrite(1);
        KeyRewrite k2 = new KeyRewrite(1);
        HashMap<KeyRewrite, String> hashMap = new HashMap<>();
        hashMap.put(k1, "Key with id is 1");
        System.out.println(hashMap.get(k2));
    }
}
